<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      title="产品物料管理"
      :columns="columns"
      :request-api="getMaterialList"
      :init-param="initParam"
      :data-callback="dataCallback"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" :icon="CirclePlus" @click="handleAdd">新增</el-button>
        <el-button type="success" :disabled="!scope.isSelected" @click="handleBatchEnable(scope.selectedListIds)">
          批量启用
        </el-button>
        <el-button type="warning" :disabled="!scope.isSelected" @click="handleBatchDisable(scope.selectedListIds)">
          批量禁用
        </el-button>
        <el-button :icon="Download" @click="handleExport">导出</el-button>
      </template>

      <!-- 物料编码 -->
      <template #materialCode="scope">
        <el-tag type="info" size="small">{{ scope.row.materialCode }}</el-tag>
      </template>

      <!-- 规格型号 -->
      <template #specification="scope">
        <div v-if="scope.row.specification || scope.row.model">
          <div v-if="scope.row.specification">规格: {{ scope.row.specification }}</div>
          <div v-if="scope.row.model">型号: {{ scope.row.model }}</div>
        </div>
        <span v-else>-</span>
      </template>

      <!-- 标准成本 -->
      <template #standardCost="scope">
        <div v-if="scope.row.standardCost" style="display: flex; align-items: center; justify-content: flex-end; gap: 4px">
          <el-icon color="#E6A23C"><Money /></el-icon>
          <span style="font-weight: 600; color: #e6a23c">{{ scope.row.standardCost.toFixed(2) }}</span>
        </div>
        <span v-else>-</span>
      </template>

      <!-- 状态 -->
      <template #status="scope">
        <el-tag :type="scope.row.status === 'ACTIVE' ? 'success' : 'warning'">
          {{ scope.row.status === "ACTIVE" ? "启用" : "禁用" }}
        </el-tag>
      </template>

      <!-- 创建时间 -->
      <template #createdTime="scope">
        <span>{{ formatDateTime(scope.row.createdTime) }}</span>
      </template>

      <!-- 操作 -->
      <template #operation="scope">
        <el-button type="primary" link @click="handleViewInDrawer(scope.row)">查看</el-button>
        <el-button type="primary" link :icon="EditPen" @click="handleEdit(scope.row)">编辑</el-button>
        <el-button :type="scope.row.status === 'ACTIVE' ? 'warning' : 'success'" link @click="handleStatusToggle(scope.row)">
          {{ scope.row.status === "ACTIVE" ? "禁用" : "启用" }}
        </el-button>
        <el-button type="danger" link :icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
      </template>
    </ProTable>

    <!-- 表单抽屉 -->
    <MaterialDrawer ref="drawerRef" />
    
    <!-- 详情抽屉 -->
    <MaterialDetail ref="detailRef" />
  </div>
</template>

<script setup lang="ts" name="productMaterial">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { CirclePlus, EditPen, Delete, Money, Download } from "@element-plus/icons-vue";
import { ColumnProps } from "@/components/ProTable/interface";
import ProTable from "@/components/ProTable/index.vue";
import MaterialDrawer from "./form.vue";
import MaterialDetail from "./detail.vue";
import {
  getMaterialList,
  createMaterial,
  updateMaterial,
  deleteMaterial,
  enableMaterial,
  disableMaterial,
  type Material
} from "@/api/modules/material";
import { getActiveMaterialGroups } from "@/api/modules/materialGroup";

// ProTable 实例
const proTable = ref();

// 物料群组选项
const materialGroupOptions = ref<Array<{ label: string; value: string }>>([]);

// 格式化时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return "-";
  return new Date(dateTime).toLocaleString("zh-CN");
};

// 状态选项
const statusOptions = [
  { label: "启用", value: "ACTIVE" },
  { label: "禁用", value: "INACTIVE" }
];

// 表格配置项
const columns: ColumnProps[] = [
  { type: "selection", fixed: "left", width: 50 },
  { type: "index", label: "#", width: 80 },
  {
    prop: "materialCode",
    label: "物料编码",
    width: 120,
    search: { el: "input", props: { placeholder: "请输入物料编码" } }
  },
  {
    prop: "materialName",
    label: "物料名称",
    width: 150,
    search: { el: "input", props: { placeholder: "请输入物料名称" } }
  },
  {
    prop: "groupName",
    label: "物料群组",
    width: 120,
    search: {
      el: "select",
      props: { placeholder: "请选择物料群组" },
      key: "groupId"
    },
    enum: materialGroupOptions
  },
  {
    prop: "specification",
    label: "规格型号",
    width: 150
  },
  {
    prop: "unit",
    label: "单位",
    width: 80,
    align: "center"
  },
  {
    prop: "standardCost",
    label: "标准成本",
    width: 120,
    align: "right"
  },
  {
    prop: "status",
    label: "状态",
    width: 80,
    search: {
      el: "select",
      props: { placeholder: "请选择状态" }
    },
    enum: statusOptions
  },
  {
    prop: "description",
    label: "描述",
    minWidth: 150,
    showOverflowTooltip: true
  },
  {
    prop: "createdTime",
    label: "创建时间",
    width: 160
  },
  {
    prop: "operation",
    label: "操作",
    width: 320,
    fixed: "right"
  }
];

// 初始化参数
const initParam = reactive({});

// 数据回调处理
const dataCallback = (data: any) => {
  return {
    list: data.records || [],
    total: Number(data.total) || 0
  };
};

// 表单抽屉引用
const drawerRef = ref<InstanceType<typeof MaterialDrawer>>();
// 详情抽屉引用
const detailRef = ref<InstanceType<typeof MaterialDetail>>();

// 获取物料群组选项
const getMaterialGroupOptions = async () => {
  try {
    const { data } = await getActiveMaterialGroups();
    materialGroupOptions.value = data.map(item => ({
      label: item.groupName,
      value: item.id
    }));
  } catch (error) {
    console.error("获取物料群组选项失败:", error);
  }
};

// 获取表格数据列表
const getTableList = () => {
  proTable.value?.getTableList();
};

// 新增
const handleAdd = () => {
  const params = {
    title: "新增",
    isView: false,
    row: {},
    api: addMaterial,
    getTableList
  };
  drawerRef.value?.acceptParams(params);
};

// 编辑
const handleEdit = (row: Material.MaterialListItem) => {
  const params = {
    title: "编辑",
    isView: false,
    row: { ...row },
    api: editMaterial,
    getTableList
  };
  drawerRef.value?.acceptParams(params);
};

// 查看
const handleViewInDrawer = (row: Material.MaterialListItem) => {
  const params = {
    row: { ...row },
    onEdit: handleEdit
  };
  detailRef.value?.acceptParams(params);
};

// 新增物料
const addMaterial = async (params: Material.CreateMaterialRequest) => {
  return await createMaterial(params);
};

// 编辑物料
const editMaterial = async (params: Material.MaterialListItem) => {
  return await updateMaterial(params.id, params);
};

// 删除
const handleDelete = async (row: Material.MaterialListItem) => {
  try {
    await ElMessageBox.confirm(`确认删除物料 "${row.materialName}" 吗？`, "删除确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
      message: `<p>删除后将无法恢复，请谨慎操作！</p><p>物料编码：${row.materialCode}</p><p>物料名称：${row.materialName}</p>`
    });

    await deleteMaterial(row.id);
    ElMessage.success("删除成功");
    getTableList();
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

// 启用/禁用状态切换
const handleStatusToggle = async (row: Material.MaterialListItem) => {
  try {
    const action = row.status === "ACTIVE" ? "禁用" : "启用";
    await ElMessageBox.confirm(`确认${action}物料 "${row.materialName}" 吗？`, `${action}确认`, {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    if (row.status === "ACTIVE") {
      await disableMaterial(row.id);
    } else {
      await enableMaterial(row.id);
    }

    ElMessage.success(`${action}成功`);
    getTableList();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("操作失败");
    }
  }
};

// 批量启用
const handleBatchEnable = async (ids: string[]) => {
  if (!ids.length) {
    ElMessage.warning("请选择要启用的物料");
    return;
  }

  try {
    await ElMessageBox.confirm(`确认启用选中的 ${ids.length} 个物料吗？`, "批量启用确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    const promises = ids.map(id => enableMaterial(id));
    await Promise.all(promises);
    ElMessage.success("批量启用成功");
    getTableList();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("批量启用失败");
    }
  }
};

// 批量禁用
const handleBatchDisable = async (ids: string[]) => {
  if (!ids.length) {
    ElMessage.warning("请选择要禁用的物料");
    return;
  }

  try {
    await ElMessageBox.confirm(`确认禁用选中的 ${ids.length} 个物料吗？`, "批量禁用确认", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    const promises = ids.map(id => disableMaterial(id));
    await Promise.all(promises);
    ElMessage.success("批量禁用成功");
    getTableList();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("批量禁用失败");
    }
  }
};

// 导出数据
const handleExport = async () => {
  try {
    ElMessage.info("正在导出数据...");
    // 这里可以调用导出API
    // const searchParam = proTable.value?.searchParam;
    // await exportMaterialList(searchParam);
    ElMessage.success("导出成功");
  } catch (error) {
    ElMessage.error("导出失败");
  }
};

// 页面加载时获取数据
onMounted(() => {
  getMaterialGroupOptions();
});
</script>

<style scoped>
</style>